<?php

namespace app\admin\controller\flow;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Log;
use app\common\constant;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Deptuser extends Backend
{
    /**
     * Department模型对象
     * @var \app\admin\model\flow\Department
     */
    protected $model = null;
    protected $userModel = null;
    //当前组别列表数据
    protected $groupdata = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\flow\Department;
        $this->userModel = new \app\admin\model\Admin;
        $all = collection($this->model->select())->toArray();
        foreach ($all as $k => $v) {
            $state = ['opened' => true];

            $channelList[] = [
                'id' => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text' => __($v['name']),
                'type' => 'dept',
                'state' => $state
            ];
        }
        $this->assignconfig('deptList', $channelList);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function getuserbydept()
    {
        if ($this->request->isAjax()) {
            $dept_id = $this->request->request('department_id');

            $deptList=$this->model->select();
            $deptName = [];
            foreach ($deptList as $k => $v) {
                $deptName[$v['id']] =$v['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->userModel
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $total = $this->userModel
                ->where($where)
                ->order($sort, $order)
                ->count();
            foreach ($list as $k => $v) {
                 $v['dept_name']=isset($deptName[$v['department_id']])?$deptName[$v['department_id']]:'';
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->userModel->allowField(true)->save(['department_id' => $params['department_id']], ['id' => $params['id']]);                  
                    Db::commit();
                }
                catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                }
                else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $groupList = collection($this->model->select())->toArray();

        Tree::instance()->init($groupList);
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        $this->view->assign('groupdata', $groupName);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->userModel->get($ids);      
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $depts = $this->request->post("departments/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    $isExsit= Db::name('flow_right')->where(['type'=>'dept','key'=>$ids])->find();
                    $admin = $this->userModel->get($ids);
                    $deptId= $admin['department_id'];

                    $dataset = '';
                    foreach ($depts as $value) {
                        $dataset = $dataset.$value.',';
                    }
                    if($deptId && $dataset){
                        if(strpos($dataset,strval($deptId))<0){
                            $dataset= $dataset.$deptId;
                        }                      
                    }
                    if($isExsit){
                        Db::name('flow_right')->where(['type'=>'dept','key'=>$ids])->update(['value'=>$dataset]);
                    }
                    else{
                        Db::name('flow_right')->insert(['type'=>'dept','key'=>$ids,'value'=>$dataset]);
                    }
                                                         
                    Db::commit();
                }
                catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                }
                else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取部门生成树
        $groupList = collection($this->model->select())->toArray();
        Tree::instance()->init($groupList);
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        //获取已授权部门
        $already = Db::name('flow_right')->where(['key'=>$ids,'type'=>'dept'])->find();
        //$depts = [];
        //foreach ($already as $k => $v)
        //{
        //    $depts[] = $v['value'];
        //}
        $this->groupdata = $groupName;
        $this->view->assign('depts', $already['value']);
        $this->view->assign('groupdata', $groupName);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 同步
     */
    public function synchronism()
    {
        $allRow    = 5000;
        $PageCount = 10;
        //初始化
        $currentPage = 1; //当前页为1
        $currentRow  = 0; //当前行为0
        while($currentPage <= $PageCount) {
            $insert = [];
            $groupinsert = [];
            //计算当前页待处理行数
            if($allRow - $currentRow >1000) {
                //剩余处理行数大于1000行
                $maxRow =  $currentRow + 1000;
            }
            else {
                $maxRow =  intval($allRow);
            }

            //获取数据
            $url = 'http://223.2.199.169:8888/getREST_TYJK_JZGXXV2_4d23e7f354c24244b245f90641a96bae';
            $header=['applyId:00000005036_1661920559819','secretKey:1237d02d-0496-40c0-97d1-40d4bbfb3968','Content-Type:application/json'];
            $params  =['YXZT'=>'有效'];
            $content =['format'=>'JSON','page'=>$currentPage,'pagesize'=>1000,'params'=>$params];
            Log::info("当前页：".$currentPage);
            $data = constant\Common::getSynchronism($url,$header,$content);

//            if(empty($data)) {
//                $file = '/uploads/20220917/3967a19b7009fd8a03fdd207704b6d1e.json';
//                $filePath = ROOT_PATH . DS . 'public' . DS . $file;
//                if (!is_file($filePath)) {
//                    $this->error(__('No results were found'));
//                }
//                $data = json_decode(file_get_contents($filePath),true);
//                return false;
//            }

            $row =[];
            $relationship = [];
            $group = [];
            if(isset($data['status']) && $data['status'] == 200 && isset($data['data']['Rows']) && !empty($data['data']['Rows'])) {
                //获取最新数量
                $allRow      = $data['total'];
                Log::info("总条数：".$allRow);
                $PageCount   = $allRow/1000+1;   //以1000条为一页处理数据，获取总页数
                foreach ($data['data']['Rows'] as $k => $v) {
                    $adminid = 0;
//                    if(isset($v['SFZJH']) && !empty($v['SFZJH'])) {
//                        $adminid = Db::name('admin')->where(['no_number' => $v['SFZJH']])->value('id');
//                    }
//                    elseif (isset($v['ZGH']) && !empty($v['ZGH'])) {
//                        $adminid = Db::name('admin')->where(['username' => $v['ZGH']])->value('id');
//                    }

                    if (isset($v['ZGH']) && !empty($v['ZGH'])) {
                        $adminid = Db::name('admin')->where(['username' => $v['ZGH']])->value('id');
                    }

                    //增量更新

                    if($adminid <1) {
                        $row['major']               = $v['EJXKDM_TEXT'];     //二级学科（专业）
                        $row['email']               = $v['DZXX'];            //电子邮箱
                        $row['mobile']              = $v['SJH'];             //手机号
                        $row['salt']                = 'wsdrjN';
                        $row['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                        //$row['password']            = substr($row['mobile'],-6); // 密码为手机号后6位
                        $row['password']            = 'a13ca3d4b7bc8b9984d8a181cb630c9d'; // 固定密码
                        //$row['password']            = md5(md5($row['password']).$row['salt']);
                        $row['employee_number']     = $v['ZGH'];             //职工号
                        $row['nickname']            = $v['XM'];              //姓名
                        $row['no_number']           = $v['SFZJH'];           //身份证件号
                        $row['education_code']      = $v['ZGXLDM'];          //最高学历代码
                        $row['degree_code']         = $v['XWDM'];            //学位代码
                        $row['research_direction']  = $v['YJFX'];            //研究方向
                        $row['education']           = $v['ZGXLDM_TEXT'];     //最高学历
                        $row['degree']              = $v['XWDM_TEXT'];       //学位
                        $row['professional_ranks']  = $v['ZYJSZWDM_TEXT'];   //专业技术职务（职称）
                        $row['createtime']          = time();
                        $row['createtime']          = time();
                        $row['updatetime']          = time();
                        $row['status']              = 'normal';

                        //插入职工数据
                        $row['username']            = $v['ZGH'];             //用户名为工号

                        //更新职工与部门关系
                        if(isset($v['SZDWDM']) && !empty($v['SZDWDM'])) {
                            $departmentid = Db::name('department')->where(['code' => $v['SZDWDM']])->value('id');
                            $relationship['department_id'] = $departmentid;
                            $relationship['organise_id']   = $departmentid;
                            $relationship['admin_id']      = $adminid;
                            $relationship['create_time']   = time();
                            $relationship['update_time']   = time();
                            $insert[] = $relationship;
                            $row['department_id'] = $departmentid;
                        }

                        $adminid = Db::name('admin')->insertGetId($row);

                        //更新职工与角色组关系
                        $group['uid']        = $adminid;
                        $group['group_id']   = 8;
                        $groupinsert[] = $group;
                    }
                    else {
                        //Db::name('admin')->where('id', $adminid)->update($row);
                    }
                }
                Db::name("department_admin")->insertAll($insert);
                Db::name("auth_group_access")->insertAll($groupinsert);
            }
            elseif(isset($data['status']) && $data['status'] == 200) {
                if(isset($data['data']['Rows']) && !empty($data['data']['Rows'])) {
                    Log::info("有问题：".json_decode($data));
                }
                else {
                    Log::info("无数据,消息：".$data['msg']."错误码：".$data['status']);
                }
            }
            else {
                if(isset($data['msg']) && $data['status'] != 200) {
                    Log::info("错误信息：".$data['msg']."错误码：".$data['status']);
                }
                return false;
            }
            $currentPage++; //当前页导入完成，当前页+1
            $currentRow = $maxRow; //当前行等于当前最大处理行+1
        }
        return true;
    }
}
